﻿using System;
using VideoStore.Domain.Entities;
using System.Linq;

namespace VideoStore.Domain.DAL
{
    public interface IOrderDataAccess
    {
        /// <summary>
        /// Gets the order by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        Order GetOrderById(Guid id);

        /// <summary>
        /// Creates the order.
        /// </summary>
        /// <param name="newOrder">The new order.</param>
        /// <returns></returns>
        Order CreateOrder(Order newOrder);

        /// <summary>
        /// Udpates the order.
        /// </summary>
        /// <param name="modifiedOrder">The modified order.</param>
        /// <returns></returns>
        Order UdpateOrder(Order modifiedOrder);
    }

    public class OrderDataAccess : BaseDataAccess, IOrderDataAccess
    {
        #region Implementation of IOrderDataAccess

        /// <summary>
        /// Gets the order by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Order GetOrderById(Guid id)
        {
            Order order = DataContext.Orders.SingleOrDefault(c => c.id == id);
            return order;
        }

        /// <summary>
        /// Creates the order.
        /// </summary>
        /// <param name="newOrder">The new order.</param>
        /// <returns></returns>
        public Order CreateOrder(Order newOrder)
        {
            newOrder.Customer = DataContext.Customers.Single(c => c.id == newOrder.customer_id);
            newOrder.Store = DataContext.Stores.Single(s => s.id == newOrder.store_id);
            newOrder.Warehouse = DataContext.Warehouses.Single(w => w.id == newOrder.warehouse_id);
            double orderTotal = 0D;
            foreach (var orderLine in newOrder.Orderlines)
            {
                Orderline temp = orderLine;
                var cat = DataContext.Catalogues.Single(c => c.id == temp.catalogue_id);
                orderLine.Catalogue = cat;
                orderTotal += cat.price;
            }
            newOrder.total = orderTotal;
            DataContext.Orders.InsertOnSubmit(newOrder);
            DataContext.SubmitChanges();
            return newOrder;
        }

        /// <summary>
        /// Udpates the order.
        /// </summary>
        /// <param name="modifiedOrder">The modified order.</param>
        /// <returns></returns>
        public Order UdpateOrder(Order modifiedOrder)
        {
            var originalEntity = DataContext.Orders.Single(o => o.id == modifiedOrder.id);
            originalEntity.status = modifiedOrder.status;
            DataContext.SubmitChanges();
            return originalEntity;
        }

        #endregion
    }
}
